#! /usr/bin/env python3
#
# Load stats.json files produced by 'semgrep-core -parsing_stats -json'
# and upload the parsing rate to the semgrep dashboard, resulting in
# a nice graph such as
#
#   https://dashboard.semgrep.dev/metric/semgrep.core.javascript.parse.pct
#
import json
import sys
import urllib.request
from collections import namedtuple
from typing import List

HOST = "https://dashboard.semgrep.dev"

Stat = namedtuple("Stat", ["lang", "line_count", "parse_success", "translation_rate"])


#
# Return an array of 0 or 1 dicts, whose field values will be posted over HTTP.
# See Parsing_stats.atd for the input format.
#
def load_stat_file(in_file: str) -> List[Stat]:
    res = []
    with open(in_file) as f:
        root = json.load(f)

    lang = root["language"]
    stat = root["global"]
    line_count = stat["line_count"]
    parse_success = stat["parsing_rate"]
    translation_rate = 1 - (stat["untranslated_node_count"] / stat["total_node_count"])

    if lang is not None and line_count is not None and parse_success is not None:
        res.append(
            Stat(
                lang=lang,
                line_count=line_count,
                parse_success=parse_success,
                translation_rate=translation_rate,
            )
        )
    return res


def upload_stats(stats: List[Stat]) -> None:
    for stat in stats:
        url = f"{HOST}/api/metric/semgrep.core.{stat.lang}.parse.pct"
        r = urllib.request.urlopen(  # nosemgrep
            url=url,
            data=str(100 * stat.parse_success).encode("ascii"),
        )
        print(r.read().decode())
        url = f"{HOST}/api/metric/semgrep.core.{stat.lang}.parse-coverage-lines.num"
        r = urllib.request.urlopen(  # nosemgrep
            url=url, data=str(stat.line_count).encode("ascii")
        )
        print(r.read().decode())
        url = f"{HOST}/api/metric/semgrep.core.{stat.lang}.parse-translation-rate.pct"
        r = urllib.request.urlopen(  # nosemgrep
            url=url, data=str(100 * stat.translation_rate).encode("ascii")
        )
        print(r.read().decode())


if __name__ == "__main__":
    if len(sys.argv) > 1:
        in_file = sys.argv[1]
        stats = load_stat_file(in_file)
        upload_stats(stats)
    else:
        print("please give a path to stats.json as the first argument")
        sys.exit(1)
